package com.yuma.lock;

import java.util.concurrent.locks.ReentrantLock;

public class TryTimeLock {

    private static final Object lock1 = new Object();
    private static final Object lock2 = new Object();

    public static void main(String[] args) {
        ReentrantLock lock = new ReentrantLock();
        ReentrantLock lock2 = new ReentrantLock();

        new Thread(() -> {
            if (lock.tryLock()){
                System.out.println("Thread 1: Holding lock 1...");
                try {
                    Thread.sleep(500); // Simulate some work
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Thread 1: Waiting for lock 2...");

                if (lock2.tryLock()) { // 如果lock2尝试加锁失败，没有竞争到锁，则释放掉第一把锁
                    System.out.println("Thread 1: Both locks acquired.");
                    // 进来了就是抢到了释放第二把锁
                    lock2.unlock();
                }
                // 释放
                lock.unlock();
            }
        }).start();


        new Thread(() -> {
            if(lock2.tryLock()) {
                System.out.println("Thread 2: Holding lock 2...");
                try {
                    Thread.sleep(500); // Simulate some work
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Thread 2: Waiting for lock 1...");
                if (lock.tryLock()) {
                    System.out.println("Thread 2: Both locks acquired.");
                    lock.unlock();
                }
                lock2.unlock();
            }
        }).start();

    }
}
